package com.example.shirodemo.config.custom;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;

/**
 * @author 绫小路
 * @date 2021/1/16 2:50
 * @description 自定义缓存，可自行自定义redis缓存
 */
public class CustomShiroCache implements CacheManager {

  public static Map<String, Object> map = new HashMap<>();

  @Override
  public <K, V> Cache<K, V> getCache(String s) throws CacheException {
    return new Cache<K, V>() {
      @Override
      public V get(K k) throws CacheException {
        return (V) map.get(k.toString());
      }

      @Override
      public V put(K k, V v) throws CacheException {
        map.put(k.toString(), v);
        return v;
      }

      @Override
      public V remove(K k) throws CacheException {
        return (V) map.remove(k.toString());
      }

      @Override
      public void clear() throws CacheException {
        map.clear();
      }

      @Override
      public int size() {
        return map.size();
      }

      @Override
      public Set<K> keys() {
        Set<K> keys = (Set<K>) map.keySet();
        return !keys.isEmpty() ? Collections.unmodifiableSet(keys) : Collections.emptySet();
      }

      @Override
      public Collection<V> values() {
        Collection<V> values = (Collection<V>) map.values();
        return (Collection)(!values.isEmpty() ? Collections.unmodifiableCollection(values) : Collections.emptyList());
      }

      @Override
      public String toString() {
        return map.toString();
      }
    };
  }
}
